package com.ln.dao;

import java.io.Serializable;
import java.util.List;

import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;

import com.ln.dto.ResultList;
import com.ln.dto.ResultObj;
import com.ln.dto.ParamsMap;
import com.ln.mapper.SqlMapper;
import com.ln.pojo.BasePOJO;

public abstract class BaseDAO<T extends BasePOJO, PK extends Serializable>
		extends SqlSessionDaoSupport implements IBaseDAO<T, PK> {

	@Autowired
	protected SqlMapper sqlMapper;

	protected Class<T> _class;

	public BaseDAO(final Class<T> _class) {
		this._class = _class;
	}

	@Override
	public int count(final ParamsMap paramsMap) {
		try {
			if (paramsMap == null || paramsMap.isEmpty()) {
				return sqlMapper.count(_class.newInstance().getTable());
			}
			return getSqlSession().selectOne(_class.getSimpleName() + ".count",
					paramsMap);
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return 0;
	}

	public final ResultObj find(final PK id) {
		return getSqlSession().selectOne(_class.getSimpleName() + ".findOne",
				id);
	}

	public T selectOne(PK id) {
		return getSqlSession().selectOne(_class.getSimpleName() + ".selectOne",
				id);
	}

	public final ResultList find(final ParamsMap paramsMap) {
		List<ResultObj> list = getSqlSession().selectList(
				_class.getSimpleName() + ".findList", paramsMap);
		return new ResultList(list);
	}

	public int update(final T pojo) {
		return getSqlSession().update(_class.getSimpleName() + ".update", pojo);
	}

	public int insert(final T pojo) {
		return getSqlSession().insert(_class.getSimpleName() + ".insert", pojo);
	}

	public int delete(PK id) {
		return getSqlSession().delete(_class.getSimpleName() + ".delete", id);
	}
	
	public int deleteByObj(T pojo) {
		return getSqlSession().delete(_class.getSimpleName() + ".deleteByObj", pojo);
	}

}
